<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\api\controller;

class Wechat extends Base
{
    /**
     * 公众号配置
     */
    public $config = [];

    /**
     * 逻辑对象
     */
    public $logic_obj;

    /**
     * 是否来自于微信的服务器配置验证
     */
    public $is_check_signature = false;

    /**
     * 逻辑对象
     */
    public $users = [];

    /**
     * 逻辑对象
     */
    public $users_id = 0;

    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();
        
        if (session('?users')) {
            $this->users = session('users');
            $this->users_id = !empty($this->users) ? $this->users['users_id'] : 0;
        }

        //获取配置
        $conf_wechat = tpSetting("OpenMinicode.conf_wechat");
        if (!empty($conf_wechat)) {
            $this->config = json_decode($conf_wechat, true);
        }
        if (empty($this->config['wait_access'])) {
            exit($_GET["echostr"]);
        }

        $echostr = isset($_GET['echostr']) ? $_GET['echostr'] : ''; // 是否来自于微信的服务器配置验证
        if ($echostr) {
            $this->is_check_signature = true;
        }else{
            $this->is_check_signature = false;
            $this->logic_obj = new \app\api\logic\WechatLogic($this->config);
        }
    }
    
    /**
     * 服务器地址(用户消息和开发者需要的事件推送，会被转发到该URL中)
     */
    public function valid()
    {
        if ($this->is_check_signature) {
            $this->checkSignature();
        }else{
            $this->logic_obj->responseMsg();
        }
    }

    /**
    * 开发者对签名（即signature）的效验，来判断此条消息的真实性
    * @return [type] [description]
    */
    public function checkSignature()
    {
        //微信会发送4个参数到我们的服务器后台 签名 时间戳 随机字符串 随机数
        $signature = $_GET['signature']; // 签名
        $timestamp = $_GET['timestamp']; // 时间戳
        $echoStr = $_GET['echostr']; // 随机字符串
        $nonce = $_GET['nonce']; // 随机数
        if ($signature && $timestamp && $echoStr && $nonce) {
            // 微信公众号基本配置中的token
            $token = $this->config['token'];
            //将token、timestamp、nonce按字典序排序
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            // 将三个参数字符串拼接成一个字符串进行sha1加密 
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
            if($tmpStr == $signature){
                header('content-type:text');
                exit($echoStr);
            } else {
                exit('');
            }
        }
    }

    /**
     * 用户关注并绑定公众号
     * 传入参数： 会员users_id
     * 返回数据： 关注微信公众号的二维码链接
     */
    public function eyou_get_qrcode()
    {
        if (!empty($this->users)) {
            $always_show = input('param.always_show/d');
            $is_refresh = input('param.is_refresh/d');
            if (empty($this->users['wechat_followed']) || !empty($always_show)) { // 未关注微信公众号则执行
                $qrcodeurl = UPLOAD_PATH.'qrcode_tmp/'.$this->users_id.'/'.md5($this->users_id).'.jpg';
                if (false && empty($is_refresh) && file_exists($qrcodeurl)) {
                    $redata = [
                        'code'  => 1,
                        'url'   => request()->domain().$this->root_dir . '/' . $qrcodeurl,
                    ];
                } else {
                    $data = [
                        'users_id'  => $this->users_id,
                    ];
                    $redata = $this->eyou_get_qrcodeurl($data);
                }

                if (1 == $redata['code'] && !empty($redata['url'])) {
                    $res = [
                        'code' => 2,
                        'msg'  => '扫码关注公众号',
                        'url'  => $redata['url'].'?v='.getVersion(),
                    ];
                } else {
                    $res = [
                        'code' => 0,
                        'msg'  => 'token失效，联系在线客服转交技术！'
                    ];
                }
            } else {
                $res = [
                    'code' => 1,
                    'msg'  => 'success',
                ];
            }
        } else {
            $res = [
                'code' => -1,
                'msg'  => '请先登录'
            ];
        }
        exit(json_encode($res));
    }

    /**
     * 获取带参数的公众号二维码
     */
    private function eyou_get_qrcodeurl($data = [])
    {
        if (!empty($data['users_id'])) {
            $origin_type = !empty($post['origin_type']) ? $post['origin_type'] : 'eyou_users';
            $WechatQrcodeUrl = $this->logic_obj->GetWechatQrcodeUrl($data['users_id'], $origin_type);
            if (empty($WechatQrcodeUrl)) {
                $WechatQrcodeUrl = $this->logic_obj->GetWechatQrcodeUrl($data['users_id'], $origin_type, true);
            }
            if (!empty($WechatQrcodeUrl)) {
                $WechatQrcodeUrl = request()->domain().$this->root_dir . '/' . $WechatQrcodeUrl;
                return ['code' => 1, 'url' => $WechatQrcodeUrl];
            }
        }
        return ['code' => 0, 'url' => ''];
    }
}